#crud
from sprox.tablebase import TableBase
from sprox.formbase import EditableForm, AddRecordForm
from sprox.fillerbase import TableFiller, EditFormFiller
#turbogears
from tgext.crud import CrudRestController
from tg import expose,require, flash
from tg.controllers import redirect
from tg.decorators import validate

from formencode import validators
from pydive.validators.user import UserRegisterValidator
from repoze.what import predicates
from pylons.i18n import ugettext as _
#model
from pydive.model import DBSession, metadata
from pydive.model.auth import User,Group

class UserController(CrudRestController):
    model = User
        
    #@expose('tgext.crud.templates.get_all')
    @require(predicates.has_permission('manage', msg=_('Only for managers')))
    @expose('pydive.templates.users.get_all')
    def get_all(self, *args, **kw):
        return super(UserController, self).get_all(*args, **kw)
    
    #@expose('pydive.templates.rest.users.get_all')
    @expose('pydive.templates.users.new')
    def new(self, *args, **kw):
        return super(UserController, self).new(*args, **kw)
    
    @expose()
    @validate(validators=UserRegisterValidator(), error_handler=new)
    def post(self,user_name,password,password_confirm,display_name,email_address):
        newUser = User(user_name=user_name,password=password,display_name=display_name,email_address=email_address)
        newUser.groups.append(DBSession.query(Group).filter(Group.group_name == 'new_users').all()[0])
        DBSession.save(newUser)
        #send registration email
        flash(_('You can now log in using your username and password'))
        redirect('/')
    
    @expose('pydive.templates.users.post_new')
    def post_new(self, user):
        return dict(registereduser=user)

    class new_form_type(AddRecordForm):
        __model__ = User
       # __omit_fields__ = ['user_id', 'diver_id','groups','created','_password','diver']
    
    class edit_form_type(EditableForm):
        __model__ = User

    class edit_filler_type(EditFormFiller):
        __model__ = User
    
    class table_type(TableBase):
        __model__ = User
    
    class table_filler_type(TableFiller):
        __model__ = User
    
